from os import path
from pathlib import Path


def dict2lines(d: dict) -> []:
    lines = []
    for (k, v) in d.items():
        lines.append(str(k) + ' ' + str(v) + '\n')
    return lines


class RCfg:
    def __init__(self, cfg_path: str):
        self._var = {
            'releaser': '',
            'release_dir': '',
            'release_to': '',
            'ftp_host': '172.22.102.202',
            'ftp_user': 'wangqiang',
            'ftp_passwd': 'wangqiang',
            'ftp_fw': '/Project/Switch/DLINK-ME/Firmware/',
            'ftp_fw_backup': '/Project/Switch/DLINK-ME/Firmware/backup/',
        }
        self._cfg = cfg_path

    def load(self):
        with open(self._cfg, 'r') as f:
            lines = f.readlines()
            for line in lines:
                l = line.strip().split()
                if len(l) > 1 and l[0] in self._var:
                    self._var[l[0]] = ' '.join(l[1:])

    @staticmethod
    def var_chk(k, v) -> bool:
        if k == 'release_dir' or k == 'release_to':
            ps = v.split(',')
            for p in ps:
                if Path(path.expanduser(p)).is_dir() is False:
                    return False
            return True
        else:
            return True

    def update(self, d: dict = None, w: bool = False):
        if d:
            self._var.update(d)
        if w:
            with open(self._cfg, 'w') as f:
                f.writelines(dict2lines(self._var))

    def rls_dir_list(self) -> []:
        return [path.expanduser(p) for p in self._var['release_dir'].split(',')]

    def dump(self) -> {}:
        return self._var

    def releaser(self) -> str:
        return self._var['releaser']

    def release_to(self) -> str:
        return path.expanduser(self._var['release_to'])

    def release_dir(self) -> str:
        return self._var['release_dir']

    def ftp_host(self):
        return self._var['ftp_host']

    def ftp_user(self):
        return self._var['ftp_user']

    def ftp_passwd(self):
        return self._var['ftp_passwd']

    def ftp_fw(self):
        return self._var['ftp_fw']

    def ftp_fw_backup(self):
        return self._var['ftp_fw_backup']
